package com.ticket.web.controller.yanchu;

import com.github.pagehelper.PageInfo;
import com.ticket.common.annotation.Log;
import com.ticket.common.core.controller.BaseController;
import com.ticket.common.core.domain.AjaxResult;
import com.ticket.common.core.domain.model.LoginUser;
import com.ticket.common.core.page.TableDataInfo;
import com.ticket.common.enums.BusinessType;
import com.ticket.common.exception.ServiceException;
import com.ticket.common.utils.SecurityUtils;
import com.ticket.common.utils.poi.ExcelUtil;
import com.ticket.framework.web.service.TokenService;
import com.ticket.system.domain.YanchuOrderDetail;
import com.ticket.system.domain.vo.OrderDetailVo;
import com.ticket.system.domain.vo.TicketFolderVo;
import com.ticket.system.domain.vo.WatchRecordVo;
import com.ticket.system.service.IYanchuOrderDetailService;
import com.ticket.system.service.IYanchuTicketFolderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 订单详情Controller
 *
 * @date 2023-09-26
 */
@Api(description = "订单详情管理")
@RequestMapping("/system/detail")
@Controller
public class YanchuOrderDetailController extends BaseController {
    @Autowired
    private IYanchuOrderDetailService yanchuOrderDetailService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IYanchuTicketFolderService yanchuTicketFolderService;

    /**
     * 查询订单详情列表
     */
    @PreAuthorize("@ss.hasPermi('system:detail:list')")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(YanchuOrderDetail yanchuOrderDetail) {
        startPage();
        List<YanchuOrderDetail> list = yanchuOrderDetailService.selectYanchuOrderDetailList(yanchuOrderDetail);
        return getDataTable(list);
    }

    @ApiOperation("票务详情列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionId", value = "订单详情编码", dataType = "Long", dataTypeClass = Long.class)
    })
    @PreAuthorize("@ss.hasPermi('system:detailticket:list')")
    @GetMapping("/ticketList")
    @ResponseBody
    public TableDataInfo<OrderDetailVo> ticketList(@RequestParam(name = "sessionId") Long sessionId) {
        startPage();
        List<OrderDetailVo> list = yanchuOrderDetailService.selectOrderDetailVoList(sessionId,null,null,null);
        return getDataTable(list);
    }

    @ApiOperation("票务明细列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单编码", dataType = "Long", dataTypeClass = Long.class)
    })
    @GetMapping("/detailList")
    @ResponseBody
    public TableDataInfo<OrderDetailVo> detailList(@RequestParam(name = "orderId") Long orderId) {
        List<OrderDetailVo> list = yanchuOrderDetailService.selectOrderDetailVoList(null,null,null,orderId);
        return getDataTable(list);
    }

    @ApiOperation("场次退款详情列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionId", value = "订单详情编码", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "status", value = "2：待处理 6已退款 7退款中", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "userName", value = "持票人姓名", dataType = "String", dataTypeClass = String.class)
    })
    @PreAuthorize("@ss.hasPermi('system:detailticket:list')")
    @GetMapping("/ticketCancelList")
    @ResponseBody
    public TableDataInfo<OrderDetailVo> ticketCancelList(@RequestParam(name = "sessionId") Long sessionId,Integer status,String userName) {
        startPage();
        List<OrderDetailVo> list = yanchuOrderDetailService.selectOrderDetailCancelVoList(sessionId,status,userName);
        return getDataTable(list);
    }

    @ApiOperation("我的电子票列表")
    @ApiImplicitParam(name = "status", value = "状态 0 所有 4已验票 2：已支付", dataType = "Long", dataTypeClass = Long.class)
    @GetMapping("/myTicketList")
    @ResponseBody
    public TableDataInfo myTicketList(@RequestParam(name = "status") Integer status) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        YanchuOrderDetail yanchuOrderDetail = new YanchuOrderDetail();
        yanchuOrderDetail.setUserId(loginUser.getUser().getUserId());
        if (null != status && status != 0) {
            yanchuOrderDetail.setStatus(status);
        }
        startPage();
        List<YanchuOrderDetail> list = yanchuOrderDetailService.selectYanchuOrderDetailList(yanchuOrderDetail);
        return getDataTable(list);
    }

    /**
     * 导出订单详情列表
     */
    @PreAuthorize("@ss.hasPermi('system:detail:export')")
    @Log(title = "订单详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YanchuOrderDetail yanchuOrderDetail) {
        List<YanchuOrderDetail> list = yanchuOrderDetailService.selectYanchuOrderDetailList(yanchuOrderDetail);
        ExcelUtil<YanchuOrderDetail> util = new ExcelUtil<YanchuOrderDetail>(YanchuOrderDetail.class);
        util.exportExcel(response, list, "订单详情数据");
    }

    /**
     * 获取订单详情详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:detail:query')")
    @GetMapping(value = "/{id}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(yanchuOrderDetailService.selectYanchuOrderDetailById(id));
    }

    @ApiOperation("票务详情")
    @ApiImplicitParam(name = "id", value = "订单详情编码", dataType = "Long", dataTypeClass = Long.class)
    @GetMapping(value = "/ticketDetail")
    @ResponseBody
    public AjaxResult ticketDetail(@RequestParam(name = "id") Long id) {
        return success(yanchuOrderDetailService.selectOrderDetailVoById(id));
    }

    /**
     * 新增订单详情
     */
    @PreAuthorize("@ss.hasPermi('system:detail:add')")
    @Log(title = "订单详情", businessType = BusinessType.INSERT)
    @ResponseBody
    @PostMapping
    public AjaxResult add(@RequestBody YanchuOrderDetail yanchuOrderDetail) {
        return toAjax(yanchuOrderDetailService.insertYanchuOrderDetail(yanchuOrderDetail));
    }

    /**
     * 修改订单详情
     */
    @PreAuthorize("@ss.hasPermi('system:detail:edit')")
    @Log(title = "订单详情", businessType = BusinessType.UPDATE)
    @PutMapping
    @ResponseBody
    public AjaxResult edit(@RequestBody YanchuOrderDetail yanchuOrderDetail) {
        return toAjax(yanchuOrderDetailService.updateYanchuOrderDetail(yanchuOrderDetail));
    }

    /**
     * 删除订单详情
     */
    @PreAuthorize("@ss.hasPermi('system:detail:remove')")
    @Log(title = "订单详情", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ResponseBody
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(yanchuOrderDetailService.deleteYanchuOrderDetailByIds(ids));
    }

    @ApiOperation("生成验票二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "detailId", value = "订单详情编码", dataType = "Long", dataTypeClass = Long.class),
    })
    @PostMapping("/tickerQrCode")
    @ResponseBody
    public AjaxResult tickerQrCode(@RequestParam(name = "detailId") Long detailId,HttpServletResponse response) {
        return AjaxResult.success(yanchuOrderDetailService.createScanQrcode(detailId));
    }

    @ApiOperation("验票")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "二维码编码", dataType = "String", dataTypeClass = String.class)
    })
    @Log(title = "验票", businessType = BusinessType.EXPORT)
    @PostMapping("/ticketCheck")
    @ResponseBody
    public AjaxResult ticketCheck(@RequestParam(name = "code") String code,Long sessionId,
                                  HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        try {
            return toAjax(yanchuOrderDetailService.ticketCheck(code, loginUser.getUser().getUserId(),sessionId));
        }catch (ServiceException e){
            logger.error("ticketCheck error",e);
            throw e;
        }catch (Exception e){
            logger.error("ticketCheck error",e);
            return AjaxResult.error("系统繁忙");
        }
    }

    @ApiOperation("票号验票")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticketNo", value = "票号", dataType = "String", dataTypeClass = String.class),
    })
    @Log(title = "验票", businessType = BusinessType.EXPORT)
    @PostMapping("/ticketNoCheck")
    @ResponseBody
    public AjaxResult ticketCheckNo(@RequestParam(name = "ticketNo") String ticketNo,Long sessionId,
                                  HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        try {
            return toAjax(yanchuOrderDetailService.ticketNoCheck(ticketNo, loginUser.getUser().getUserId(), sessionId));
        }catch (ServiceException e){
            logger.error("ticketCheckNo error",e);
            throw e;
        }catch (Exception e){
            logger.error("ticketCheckNo error",e);
            return AjaxResult.error("系统繁忙");
        }
    }

    @ApiOperation("验票统计")
    @PostMapping("/tickerCheckStat")
    @ResponseBody
    public AjaxResult tickerCheckStat(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        return AjaxResult.success(yanchuOrderDetailService.ticketCheckStat(loginUser.getUser().getUserId()));
    }

    @ApiOperation("核验记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionId",value = "演出场次id",required = true,dataTypeClass = Long.class,dataType = "Long"),
            @ApiImplicitParam(name = "state",value = "全部：0; 已核验：4，未核验：2",dataTypeClass = Integer.class,dataType = "Integer"),
            @ApiImplicitParam(name = "keyName",value = "模糊匹配字段",dataTypeClass = String.class,dataType = "String"),
    })
    @GetMapping("/tickerVerification")
    @ResponseBody
    public AjaxResult tickerVerification(Long sessionId,String keyName,Integer state, HttpServletRequest request){
        LoginUser loginUser = tokenService.getLoginUser(request);
        return AjaxResult.success(yanchuOrderDetailService.tickerVerification(sessionId,keyName,loginUser.getUser().getUserId(),state));
    }

    @ApiOperation("票夹——票夹信息列表")
    @PostMapping("/ticketFolder")
    @ResponseBody
    public AjaxResult<PageInfo<TicketFolderVo>> ticketFolder(HttpServletRequest request) {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(request);
        return AjaxResult.success(yanchuTicketFolderService.applyPageTicketFolder(loginUser.getUser().getUserId(),
                loginUser.getUser().getUserinfoId(),loginUser.getUser().getPhonenumber()));
    }
    @ApiOperation("票夹——历史票根信息列表")
    @PostMapping("/historyCounterfoil")
    @ResponseBody
    public AjaxResult<PageInfo<TicketFolderVo>> historyCounterfoil(HttpServletRequest request) {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(request);
        return AjaxResult.success(yanchuTicketFolderService.applyPageHistoryCounterfoil(loginUser.getUser().getUserId(),
                loginUser.getUser().getUserinfoId(),loginUser.getUser().getPhonenumber()));
    }


    @ApiOperation("小程序 我的观看记录")
    @GetMapping("/myWatchRecord")
    @ResponseBody
    public TableDataInfo myWatchRecord(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        startPage();
        List<WatchRecordVo> list = yanchuOrderDetailService.myWatchRecord(loginUser.getUser().getUserId(),loginUser.getUser().getUserinfoId(),loginUser.getUser().getPhonenumber());
        return getDataTable(list);
    }


    @ApiOperation("票夹——票夹详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "Integer", dataTypeClass = Integer.class, required = true)
    })
    @PostMapping("/ticketFolderDetail")
    @ResponseBody
    public AjaxResult<TicketFolderVo> ticketFolderDetail(Long orderId, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        return AjaxResult.success(yanchuTicketFolderService.applyGetTicketFolderDetail(orderId, loginUser.getUser().getUserId()));
    }

}
